package com.mandao.concurrency.example.atomic;

import com.mandao.concurrency.annotations.ThreadSafe;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicStampedReference;

import static sun.misc.PostVMInitHook.run;

/**
 * 线程安全性:
 *  *   原子性:提供了互斥访问,同一时刻只能有一个线程来对它进行操作
 *  *   CAS的 ABA问题
 * @author 蜗牛
 */
@Slf4j
@ThreadSafe
public class AtomicExample6 {

    private static AtomicInteger count = new AtomicInteger(100);

    public static void main(String[] args) throws InterruptedException {

        Thread t0 = new Thread(() -> {
            run();
        });

        Thread t1 = new Thread(()-> {
                count.compareAndSet(100,101);
                count.compareAndSet(101,100);
        });

        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                boolean b = count.compareAndSet(100, 102);
                log.info("CAS 问题,{}",count.get());
            }
        });

        t1.start();
        t2.start();
        t1.join();
        t2.join();

    }

}
